package com.yx.cloud.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.makeramen.roundedimageview.RoundedImageView;
import com.yx.cloud.R;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.iot.base.bean.account.Account;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * 创建时间 : 2018/12/26.
 * 创建人 :
 * 功能描述 :
 */
public class SharEquipmentAdapter extends BaseAdapter {
    private static final String TAG = "SharEquipmentAdapter";
    Context mContext;
    List<Account> mList;
    Bitmap bitmap;

    /**
     * * 自定义接口，用于回调按钮点击事件到Activity
     */
    public interface Callback {
        public void click(View v);
    }

    private Bitmap mLoadingBitmap;

    public SharEquipmentAdapter(Context context, List list) {
        mContext = context;
        mList = list;
//        mLoadingBitmap = BitmapFactory.decodeResource(context.getResources(),
//                R.drawable.headportrait_icon);
//        // 获取应用程序最大可用内存
//        int maxMemory = (int) Runtime.getRuntime().maxMemory();
//        int cacheSize = maxMemory / 8;
//        mMemoryCache = new LruCache<String, BitmapDrawable>(cacheSize) {
//            @Override
//            protected int sizeOf(String key, BitmapDrawable drawable) {
//                return drawable.getBitmap().getByteCount();
//            }
//        };
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder mHolder;
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.sharequipment_item, null);
            mHolder = new ViewHolder();
            mHolder.mDate = convertView.findViewById(R.id.tv_date);
            mHolder.mTvWo = convertView.findViewById(R.id.tv_wo);
            mHolder.mIphoneNum = convertView.findViewById(R.id.tv_iphoneNum);
            mHolder.mShareheadPic = convertView.findViewById(R.id.iv_shareheadPic);
            mHolder.mIvSharDelete = convertView.findViewById(R.id.iv_sharDelete);

            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }

        Account bean = mList.get(position);
        String logUsername = SharedPrefsUtil.getValue(mContext, Constants.USERNAME, "username", "");
        String contryCode = SharedPrefsUtil.getValue(mContext, Constants.USERNAME, "contryCode", "");
        String mobile = bean.getAccount();

        if (mobile.equals(contryCode + "-" + logUsername)) {
            Log.i(TAG, "---------------------------");
//            mHolder.mDate.setText(mContext.getString(R.string.Main_IDa));
//            mHolder.mIphoneNum.setText(bean.getMobile());
//            mHolder.mShareheadPic.setImageBitmap(Constants.headPicbitmap);
//            mHolder.mTvWo.setVisibility(View.VISIBLE);
        } else {
            mHolder.mDate.setText(mContext.getString(R.string.MO_DeputyID));
            mHolder.mIphoneNum.setText(bean.getAccount());
            mHolder.mShareheadPic.setBackgroundResource(R.mipmap.headportrait_icon);
            Log.i(TAG, "+++++++++++++++++++++++++++++++" + mList.size());
//            String iconUrl = bean.getHeadPicUrl();
//            mHolder.mShareheadPic.setTag(iconUrl);
//            if (!iconUrl.equals("")) {
//                //异步加载网络头像
//                DownImgTask downImgTask = new DownImgTask(mHolder.mShareheadPic);
//                downImgTask.execute(iconUrl);
//            } else {
//                mHolder.mShareheadPic.setBackgroundResource(R.mipmap.headportrait_icon);
//            }
        }
        return convertView;
    }

    class ViewHolder {
        TextView mDate;
        TextView mIphoneNum;
        TextView mTvWo;
        ImageView mIvSharDelete;
        RoundedImageView mShareheadPic;
    }

    class DownImgTask extends AsyncTask<String, Void, Bitmap> {
        ImageView iv;
        String img_url;// 图片的地址

        public DownImgTask(ImageView iv) {
            super();
            this.iv = iv;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            img_url = params[0];
            HttpURLConnection conn = null;
            Bitmap bm = null;
            try {
                URL url = new URL(img_url);
                conn = (HttpURLConnection) url.openConnection();
                InputStream in = conn.getInputStream();
                bm = BitmapFactory.decodeStream(in);
                in.close();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return bm;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
            super.onPostExecute(result);

/**
 * 防止ListView异步加载图片错位、重复、闪烁等情况
 * 判断下tag值和图片地址是否相等，若相等，则说明该控件在当前的位置所需要展示的图片 是对的，就可以直接展示出来啦
 */
            // 防止图片错位，判断下tag值和图片地址是否相等
            if (result != null && img_url.equals(iv.getTag())) {
                // 设置图片
                iv.setImageBitmap(result);
            }
        }
    }


//    private void asyncloadImage(final ImageView imageView, final String uri) {
//        final Handler mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                if (msg.what == 1) {
//                    Bitmap bitmap = (Bitmap) msg.obj;
//                    if (imageView != null && uri != null) {
//                        imageView.setImageBitmap(bitmap);
//                    }
//
//                }
//            }
//        };
//        // 子线程，开启子线程去下载或者去缓存目录找图片，并且返回图片在缓存目录的地址
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //这个URI是图片下载到本地后的缓存目录中的URI
//                    if (uri != null) {
//                        Bitmap bitmap = getLocalOrNetBitmap(uri);
//                        Message msg = new Message();
//                        msg.what = 1;
//                        msg.obj = bitmap;
//                        mHandler.sendMessage(msg);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//        new Thread(runnable).start();
//    }
//
//    /**
//     * @param url 　本地或网络的url
//     * @return　url的bitmap
//     */
//    public Bitmap getLocalOrNetBitmap(String url) {
//        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.headportrait_icon);
//        if (url != null) {
//            InputStream in = null;
//            BufferedOutputStream out = null;
//            try {
//                //读取图片输入流
//                in = new BufferedInputStream(new URL(url).openStream(), 2 * 1024);
//                //准备输出流
//                final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
//                out = new BufferedOutputStream(dataStream, 2 * 1024);
//                byte[] b = new byte[1024];
//                int read;
//                //将输入流变为输出流
//                while ((read = in.read(b)) != -1) {
//                    out.write(b, 0, read);
//                }
//                out.flush();
//                //将输出流转换为bitmap
//                byte[] data = dataStream.toByteArray();
//                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//                data = null;
//                return bitmap;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return bitmap;
//            }
//        }
//        return bitmap;
//    }
}
